
package com.sanpu.kxe.module.wheel;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;

import com.sanpu.kxe.R;
import com.sanpu.kxe.business.repay.bean.AreaOutput;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;
import com.sanpu.kxe.module.wheel.adapter.ListWheelAdapter;
import com.sanpu.kxe.module.wheel.interfaces.OnWheelChangedListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Description : 地区选择滚轮
 */
public class RegionWheel implements OnWheelChangedListener {
    /**
     * 可见item个数
     */
    public static final int VISIBLE_ITEM = 7;

    /**
     * 当前item
     */
    public static final int CURRENT_ITEM = 0;

    private Context context;

    private View areaView;

    private WheelView wv_First;

    private WheelView wv_Second;

    private WheelView wv_Third;

    private List<AreaOutput.Prov> firstList;

    private List<AreaOutput.City> secondList;

    private List<AreaOutput.City> thirdList;

    private ListWheelAdapter FirstAdapter;

    private ListWheelAdapter secondAdapter;

    private ListWheelAdapter thirdAdapter;

    /**
     * 滑动停止时监听()返回字符串）
     */
    private OnWheelFinishListener onWheelFinishListener;

    private AreaOutput retDatBean;

    /**
     * 是否显示区
     */
    private boolean showDistricts;

    public RegionWheel(Context context, boolean showDistricts) {
        this(context, null, showDistricts);
    }

    public RegionWheel(Context context, View areaView, boolean showDistricts) {
        this(context, areaView, null, null, null, showDistricts);
    }

    public RegionWheel(Context context, View areaView, String first, String second, String third, boolean showDistricts) {
        this.context = context;
        this.areaView = areaView;
        this.showDistricts = showDistricts;
        initView(first, second, third);
        initListener();
    }

    public View getAreaView() {
        return areaView;
    }

    /**
     * 初始化view
     */
    private void initView(String first, String second, String third) {
        if (areaView == null) {
            LayoutInflater inflater = LayoutInflater.from(context);
            areaView = inflater.inflate(R.layout.view_wheel_area, null);
        }
        initFirstDatas();
        int provinceIndex = getIndexByProvName(first, firstList);
        // 省
        wv_First = (WheelView) areaView.findViewById(R.id.first);
        wv_First.setAdapter(FirstAdapter);// 设置省的显示数据
        wv_First.setCyclic(false);// 不可循环滚动
        wv_First.setVisibleItems(VISIBLE_ITEM);
        wv_First.setCurrentItem(provinceIndex);
        // wv_First.setRadian(WheelView.DEFAULT_LEFT_RADIAN);
        updateSecondDatas(provinceIndex);
        int cityIndex = getIndexByName(second, secondList);
        // 市
        wv_Second = (WheelView) areaView.findViewById(R.id.second);
        wv_Second.setAdapter(secondAdapter);// 设置城市的显示数据
        wv_Second.setCyclic(false);// 不可循环滚动
        wv_Second.setVisibleItems(VISIBLE_ITEM);
        wv_Second.setCurrentItem(cityIndex);
        // wv_Second.setRadian(WheelView.DEFAULT_RADIAN);

        wv_Third = (WheelView) areaView.findViewById(R.id.third);
        if (showDistricts) {
            wv_Third.setVisibility(View.VISIBLE);

            updateThirdDatas(cityIndex);
            // 地区
            wv_Third.setAdapter(thirdAdapter);// 设置区域的显示数据
            wv_Third.setCyclic(false);// 不可循环滚动
            wv_Third.setVisibleItems(VISIBLE_ITEM);
            wv_Third.setCurrentItem(getIndexByName(third, thirdList));
            // wv_Third.setRadian(WheelView.DEFAULT_RIGHT_RADIAN);
        } else {
            wv_Third.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化监听
     */
    private void initListener() {
        wv_First.addChangingListener(this);
        wv_Second.addChangingListener(this);
        if (showDistricts) {
            wv_Third.addChangingListener(this);
        }
    }

    // 存放返回字符串
    StringBuilder result = new StringBuilder();
    StringBuilder code = new StringBuilder();

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        if (wheel == wv_First) {
            updateSecondDatas(newValue);
        }
        if (wheel == wv_Second && showDistricts) {
            updateThirdDatas(newValue);
        }
        if (wheel == wv_Third  && showDistricts) {
            if (wv_Third != null) {
                wv_Third.setCurrentItem(newValue);
            }
        }
        result.delete(0, result.length());
        code.delete(0, code.length());
        result.append(firstList.get(wv_First.getCurrentItem()).getProvNm());
        code.append(firstList.get(wv_First.getCurrentItem()).getProvCd());
        if (secondList != null && secondList.size() > 0) {
            result.append(" ").append(secondList.get(wv_Second.getCurrentItem()).getCityNm());
            code.append(" ").append(secondList.get(wv_Second.getCurrentItem()).getCityCd());
        }
        if (thirdList != null && thirdList.size() > 0 && showDistricts) {
            result.append(" ").append(thirdList.get(wv_Third.getCurrentItem()).getCityNm());
            code.append(" ").append(thirdList.get(wv_Third.getCurrentItem()).getCityCd());
        }
        onWheelFinishListener.OnChange(result.toString(), code.toString());
    }

    /**
     * 更新区域
     */
    public void updateThirdDatas(int index) {
        if (secondList != null && secondList.size() > 0) {
            String code = secondList.get(index).getCityCd();
            if (retDatBean != null && !TextUtils.isEmpty(code)) {
                List<AreaOutput.City> cities = retDatBean.getCity();
                if (cities != null && !cities.isEmpty()) {
                    thirdList = new ArrayList<>();
                    for (AreaOutput.City city:cities) {
                        if (TextUtils.equals(code, city.getfCd())) {
                            thirdList.add(city);
                        }
                    }
                }
            }
        } else {
            thirdList = null;
        }
        if (thirdAdapter == null) {
            thirdAdapter = new ListWheelAdapter(context, thirdList);
        } else {
            thirdAdapter.setItems(thirdList);
        }
        if (wv_Second != null) {
            wv_Second.setCurrentItem(index);
        }
        if (wv_Third != null) {
            wv_Third.setCurrentItem(CURRENT_ITEM);
        }
    }

    /**
     * 更新城市数据
     */
    public void updateSecondDatas(int index) {
        if (firstList != null && firstList.size() > 0) {
            String code = firstList.get(index).getProvCd();
            if (retDatBean != null && !TextUtils.isEmpty(code)) {
                List<AreaOutput.City> cities = retDatBean.getCity();
                if (cities != null && !cities.isEmpty()) {
                    secondList = new ArrayList<>();
                    for (AreaOutput.City city:cities) {
                        if (TextUtils.equals(code, city.getfCd())) {
                            secondList.add(city);
                        }
                    }
                }
            }
        }
        if (secondAdapter == null) {
            secondAdapter = new ListWheelAdapter(context, secondList);
        } else {
            secondAdapter.setItems(secondList);
        }
        if (wv_First != null) {
            wv_First.setCurrentItem(index);
        }
        if (wv_Second != null) {
            wv_Second.setCurrentItem(CURRENT_ITEM);
        }
        if (wv_Third != null) {
            wv_Third.setCurrentItem(CURRENT_ITEM);
        }
//        updateThirdDatas(CURRENT_ITEM);
    }

    /**
     * 初始化省数据
     */
    private void initFirstDatas() {
        retDatBean = CacheManage.getInstance().getCache(CacheModel.AREA_ENTITY);
        if (retDatBean != null) {
            firstList = retDatBean.getProv();
        }
        if (FirstAdapter == null) {
            FirstAdapter = new ListWheelAdapter(context, firstList);
        } else {
            FirstAdapter.setItems(firstList);
        }
    }

    public interface OnWheelFinishListener {
        /**
         * 滑动停止后，当前区域
         *
         * @param currentValue 当前区域
         * @param currentCode code值
         */
        void OnChange(String currentValue, String currentCode);
    }

    /**
     * 设置滑动结束监听(字符串)
     *
     * @param wheelFinishListener 监听
     */
    public void setWheelFinishListener(OnWheelFinishListener wheelFinishListener) {
        if (this.onWheelFinishListener == null) {
            this.onWheelFinishListener = wheelFinishListener;
        }
        if (firstList != null && firstList.size() > 0) {
            result.append(firstList.get(wv_First.getCurrentItem()).getProvNm());
            code.append(firstList.get(wv_First.getCurrentItem()).getProvCd());
        }
        if (secondList != null && secondList.size() > 0) {
            result.append(" ").append(secondList.get(wv_Second.getCurrentItem()).getCityNm());
            code.append(" ").append(secondList.get(wv_Second.getCurrentItem()).getCityCd());
        }
        if (thirdList != null && thirdList.size() > 0) {
            result.append(" ").append(thirdList.get(wv_Third.getCurrentItem()).getCityNm());
            code.append(" ").append(thirdList.get(wv_Third.getCurrentItem()).getCityCd());
        }
        wheelFinishListener.OnChange(result.toString(), code.toString());
    }

    /**
     * 根据省名字获取index
     *
     * @param name      显示名字
     * @param pointList 目标列表
     * @return int
     */
    private int getIndexByProvName(String name, List<AreaOutput.Prov> pointList) {
        if (pointList == null || pointList.size() == 0 || TextUtils.isEmpty(name))
            return CURRENT_ITEM;
        int size = pointList.size();
        for (int i = 0; i < size; i++) {
            AreaOutput.Prov area = pointList.get(i);
            if (TextUtils.equals(area.getProvNm(), name)) {
                return i;
            }
        }
        return CURRENT_ITEM;
    }

    /**
     * 根据名字获取index
     *
     * @param name      显示名字
     * @param pointList 目标列表
     * @return int
     */
    private int getIndexByName(String name, List<AreaOutput.City> pointList) {
        if (pointList == null || pointList.size() == 0 || TextUtils.isEmpty(name))
            return CURRENT_ITEM;
        int size = pointList.size();
        for (int i = 0; i < size; i++) {
            AreaOutput.City area = pointList.get(i);
            if (TextUtils.equals(area.getCityNm(), name)) {
                return i;
            }
        }
        return CURRENT_ITEM;
    }
}
